#!/usr/bin/env python


# Copyright (c) 2011 by Kenneth Dixon
#
# GNU General Public Licence (GPL)
# 
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307  USA


import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
import Properties as pr
import logging
import urllib2

class Email():
    
    def __init__(self):
        self.logger = logging.getLogger(pr.LOGGER_NAME)
        self.logger.info("Email Logger Initialised")
    
    def sendSnapshotEmail(self,snapshotDir):
        self.logger.info("Sending Snapshot Email")
        msg = MIMEMultipart()
        msg['From'] = pr.EMAIL_FROM
        msg['To'] = pr.EMAIL_TO
        msg['Subject'] = pr.EMAIL_SUBJECT
        msg.attach(MIMEText(pr.EMAIL_HTML_MESSAGE_1+self.getExternalIP()+":"+pr.CAM_PORT+pr.EMAIL_HTML_MESSAGE_2, 'html'))
        
        for file in os.listdir(snapshotDir):
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(open(snapshotDir+"/"+file, 'rb').read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(snapshotDir+"/"+file))
            msg.attach(part)
        
        mailServer = smtplib.SMTP(pr.EMAIL_SERVER_SMTP, pr.EMAIL_SERVER_PORT)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(pr.EMAIL_FROM, pr.EMAIL_PASSWORD)
        mailServer.sendmail(pr.EMAIL_FROM, pr.EMAIL_TO, msg.as_string())
        mailServer.quit()
        self.logger.info("Snapshot Email Sent")
        
    def getExternalIP(self):
        return urllib2.urlopen(pr.EMAIL_EXTERNAL_IP_URL).readlines()[0]

#For Testing Only ********************************
#def main():
#    myEmail = Email()
#    myEmail.sendSnapshotEmail("/home/i/Development/pyx10controller/snapshots/20120623194941")
    
#main()
